# -*- coding: utf-8 -*-
"""
集成聚合数据API的增强版服务器
支持真实机票和火车票数据获取，智能排序功能
"""
from flask import Flask, request, jsonify, render_template_string
import json
import time
from datetime import datetime, timedelta
from juhe_api_integration import JuheAPI, SmartSorter
import os

app = Flask(__name__)

# 配置API密钥（请替换为您的真实密钥）
FLIGHT_API_KEY = "YOUR_FLIGHT_API_KEY"  # 聚合数据机票API密钥
TRAIN_API_KEY = "YOUR_TRAIN_API_KEY"    # 聚合数据火车票API密钥

# 创建API实例
juhe_api = JuheAPI(FLIGHT_API_KEY, TRAIN_API_KEY)

# 智能排序器
sorter = SmartSorter()

# 城市代码映射
CITY_CODES = {
    '北京': 'BJS', '上海': 'SHA', '广州': 'CAN', '深圳': 'SZX',
    '大连': 'DLC', '合肥': 'HFE', '南京': 'NKG', '杭州': 'HGH',
    '武汉': 'WUH', '成都': 'CTU', '重庆': 'CKG', '西安': 'SIA',
    '天津': 'TSN', '青岛': 'TAO', '沈阳': 'SHE', '哈尔滨': 'HRB',
    '长沙': 'CSX', '厦门': 'XMN', '福州': 'FOC', '济南': 'TNA',
    '郑州': 'CGO', '太原': 'TYN', '石家庄': 'SJW', '呼和浩特': 'HET'
}

@app.route('/')
def index():
    """主页"""
    return render_template_string(INDEX_TEMPLATE)

@app.route('/api/status')
def api_status():
    """API状态检查"""
    return jsonify({
        'status': 'success',
        'message': '聚合数据API服务器运行正常',
        'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'features': [
            '真实机票数据获取',
            '真实火车票数据获取',
            '智能排序功能',
            '多维度排序选项'
        ]
    })

@app.route('/api/search', methods=['POST'])
def search_travel():
    """搜索交通方式"""
    try:
        data = request.get_json()
        origin = data.get('origin', '')
        destination = data.get('destination', '')
        date = data.get('date', '')
        sort_type = data.get('sort_type', 'smart')
        
        if not origin or not destination:
            return jsonify({'error': '请提供出发地和目的地'}), 400
        
        print(f"🔍 搜索请求: {origin} → {destination} ({date})")
        
        # 获取机票数据
        flights = juhe_api.get_flight_data(origin, destination, date)
        
        # 获取火车票数据
        trains = juhe_api.get_train_data(origin, destination, date)
        
        # 合并数据
        all_data = flights + trains
        
        # 智能排序
        sorted_data = sorter.smart_sort(all_data, sort_type)
        
        # 添加排序说明
        sort_descriptions = {
            'smart': '智能排序（综合价格、时间、舒适度）',
            'price_low': '价格从低到高',
            'price_high': '价格从高到低',
            'time_early': '出发时间从早到晚',
            'time_late': '出发时间从晚到早',
            'duration_short': '行程时间从短到长',
            'duration_long': '行程时间从长到短',
            'comfort': '舒适度排序'
        }
        
        result = {
            'status': 'success',
            'data': sorted_data,
            'total': len(sorted_data),
            'flights': len(flights),
            'trains': len(trains),
            'sort_type': sort_type,
            'sort_description': sort_descriptions.get(sort_type, '未知排序'),
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
        print(f"✅ 搜索完成: 找到 {len(sorted_data)} 条结果")
        return jsonify(result)
        
    except Exception as e:
        print(f"❌ 搜索异常: {e}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/sort', methods=['POST'])
def sort_data():
    """排序数据"""
    try:
        data = request.get_json()
        travel_data = data.get('data', [])
        sort_type = data.get('sort_type', 'smart')
        
        # 智能排序
        sorted_data = sorter.smart_sort(travel_data, sort_type)
        
        sort_descriptions = {
            'smart': '智能排序（综合价格、时间、舒适度）',
            'price_low': '价格从低到高',
            'price_high': '价格从高到低',
            'time_early': '出发时间从早到晚',
            'time_late': '出发时间从晚到早',
            'duration_short': '行程时间从短到长',
            'duration_long': '行程时间从长到短',
            'comfort': '舒适度排序'
        }
        
        result = {
            'status': 'success',
            'data': sorted_data,
            'total': len(sorted_data),
            'sort_type': sort_type,
            'sort_description': sort_descriptions.get(sort_type, '未知排序'),
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
        return jsonify(result)
        
    except Exception as e:
        print(f"❌ 排序异常: {e}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/cities')
def get_cities():
    """获取支持的城市列表"""
    return jsonify({
        'status': 'success',
        'cities': list(CITY_CODES.keys()),
        'total': len(CITY_CODES)
    })

@app.route('/api/sort_options')
def get_sort_options():
    """获取排序选项"""
    return jsonify({
        'status': 'success',
        'options': [
            {'value': 'smart', 'label': '智能排序', 'description': '综合价格、时间、舒适度'},
            {'value': 'price_low', 'label': '价格从低到高', 'description': '按价格升序排列'},
            {'value': 'price_high', 'label': '价格从高到低', 'description': '按价格降序排列'},
            {'value': 'time_early', 'label': '出发时间从早到晚', 'description': '按出发时间升序排列'},
            {'value': 'time_late', 'label': '出发时间从晚到早', 'description': '按出发时间降序排列'},
            {'value': 'duration_short', 'label': '行程时间从短到长', 'description': '按行程时间升序排列'},
            {'value': 'duration_long', 'label': '行程时间从长到短', 'description': '按行程时间降序排列'},
            {'value': 'comfort', 'label': '舒适度排序', 'description': '按舒适度排序'}
        ]
    })

# HTML模板
INDEX_TEMPLATE = '''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能交通规划助手 - 聚合数据版</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }
        
        .search-section {
            padding: 30px;
            background: #f8f9fa;
        }
        
        .search-form {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr auto;
            gap: 20px;
            align-items: end;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-group label {
            font-weight: bold;
            margin-bottom: 8px;
            color: #333;
        }
        
        .form-group input, .form-group select {
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .search-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: transform 0.2s;
        }
        
        .search-btn:hover {
            transform: translateY(-2px);
        }
        
        .sort-section {
            padding: 20px 30px;
            background: white;
            border-bottom: 1px solid #e1e5e9;
        }
        
        .sort-controls {
            display: flex;
            gap: 15px;
            align-items: center;
        }
        
        .sort-controls label {
            font-weight: bold;
            color: #333;
        }
        
        .sort-controls select {
            padding: 8px 12px;
            border: 2px solid #e1e5e9;
            border-radius: 6px;
            font-size: 14px;
        }
        
        .results-section {
            padding: 30px;
        }
        
        .results-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .results-count {
            font-size: 1.2em;
            font-weight: bold;
            color: #333;
        }
        
        .results-list {
            display: grid;
            gap: 15px;
        }
        
        .result-item {
            background: white;
            border: 2px solid #e1e5e9;
            border-radius: 12px;
            padding: 20px;
            transition: all 0.3s;
            cursor: pointer;
        }
        
        .result-item:hover {
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
        }
        
        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .result-type {
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: bold;
            font-size: 1.1em;
        }
        
        .result-price {
            font-size: 1.5em;
            font-weight: bold;
            color: #e74c3c;
        }
        
        .result-details {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 15px;
            margin-bottom: 15px;
        }
        
        .detail-item {
            text-align: center;
        }
        
        .detail-label {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 5px;
        }
        
        .detail-value {
            font-weight: bold;
            color: #333;
        }
        
        .result-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.9em;
            color: #666;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            font-size: 1.2em;
            color: #666;
        }
        
        .error {
            background: #fee;
            color: #c33;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
        }
        
        .success {
            background: #efe;
            color: #3c3;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
        }
        
        .api-status {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #4CAF50;
            color: white;
            padding: 10px 20px;
            border-radius: 25px;
            font-size: 14px;
            z-index: 1000;
        }
        
        @media (max-width: 768px) {
            .search-form {
                grid-template-columns: 1fr;
            }
            
            .result-details {
                grid-template-columns: 1fr;
            }
            
            .sort-controls {
                flex-direction: column;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>
    <div class="api-status" id="apiStatus">API连接正常</div>
    
    <div class="container">
        <div class="header">
            <h1>🚀 智能交通规划助手</h1>
            <p>基于聚合数据API的真实机票和火车票数据</p>
        </div>
        
        <div class="search-section">
            <form class="search-form" id="searchForm">
                <div class="form-group">
                    <label for="origin">出发地</label>
                    <input type="text" id="origin" name="origin" placeholder="请输入出发城市" required>
                </div>
                <div class="form-group">
                    <label for="destination">目的地</label>
                    <input type="text" id="destination" name="destination" placeholder="请输入到达城市" required>
                </div>
                <div class="form-group">
                    <label for="date">出发日期</label>
                    <input type="date" id="date" name="date" required>
                </div>
                <button type="submit" class="search-btn">🔍 搜索</button>
            </form>
        </div>
        
        <div class="sort-section" id="sortSection" style="display: none;">
            <div class="sort-controls">
                <label for="sortType">排序方式：</label>
                <select id="sortType">
                    <option value="smart">智能排序</option>
                    <option value="price_low">价格从低到高</option>
                    <option value="price_high">价格从高到低</option>
                    <option value="time_early">出发时间从早到晚</option>
                    <option value="time_late">出发时间从晚到早</option>
                    <option value="duration_short">行程时间从短到长</option>
                    <option value="duration_long">行程时间从长到短</option>
                    <option value="comfort">舒适度排序</option>
                </select>
            </div>
        </div>
        
        <div class="results-section">
            <div id="resultsContainer">
                <div class="loading" id="loadingMessage" style="display: none;">
                    🔍 正在搜索中，请稍候...
                </div>
                <div id="resultsContent"></div>
            </div>
        </div>
    </div>

    <script>
        // 设置默认日期为明天
        document.getElementById('date').value = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().split('T')[0];
        
        // 搜索表单提交
        document.getElementById('searchForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const origin = document.getElementById('origin').value;
            const destination = document.getElementById('destination').value;
            const date = document.getElementById('date').value;
            
            if (!origin || !destination) {
                alert('请填写出发地和目的地');
                return;
            }
            
            await searchTravel(origin, destination, date);
        });
        
        // 排序选择变化
        document.getElementById('sortType').addEventListener('change', function() {
            const sortType = this.value;
            sortResults(sortType);
        });
        
        // 搜索交通方式
        async function searchTravel(origin, destination, date) {
            const loadingMessage = document.getElementById('loadingMessage');
            const resultsContent = document.getElementById('resultsContent');
            const sortSection = document.getElementById('sortSection');
            
            loadingMessage.style.display = 'block';
            resultsContent.innerHTML = '';
            sortSection.style.display = 'none';
            
            try {
                const response = await fetch('/api/search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        origin: origin,
                        destination: destination,
                        date: date,
                        sort_type: 'smart'
                    })
                });
                
                const data = await response.json();
                
                if (data.status === 'success') {
                    displayResults(data.data, data.total, data.flights, data.trains);
                    sortSection.style.display = 'block';
                } else {
                    showError(data.error || '搜索失败');
                }
            } catch (error) {
                showError('网络错误：' + error.message);
            } finally {
                loadingMessage.style.display = 'none';
            }
        }
        
        // 排序结果
        async function sortResults(sortType) {
            const resultsContent = document.getElementById('resultsContent');
            const currentData = window.currentResults || [];
            
            if (currentData.length === 0) return;
            
            try {
                const response = await fetch('/api/sort', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        data: currentData,
                        sort_type: sortType
                    })
                });
                
                const data = await response.json();
                
                if (data.status === 'success') {
                    displayResults(data.data, data.total, data.flights, data.trains);
                } else {
                    showError(data.error || '排序失败');
                }
            } catch (error) {
                showError('排序错误：' + error.message);
            }
        }
        
        // 显示结果
        function displayResults(results, total, flights, trains) {
            window.currentResults = results;
            
            const resultsContent = document.getElementById('resultsContent');
            
            if (results.length === 0) {
                resultsContent.innerHTML = '<div class="error">未找到相关交通信息</div>';
                return;
            }
            
            let html = `
                <div class="results-header">
                    <div class="results-count">找到 ${total} 条结果（航班 ${flights} 条，火车 ${trains} 条）</div>
                </div>
                <div class="results-list">
            `;
            
            results.forEach((item, index) => {
                const typeIcon = item.type === 'flight' ? '✈️' : '🚄';
                const typeName = item.type === 'flight' ? '航班' : '火车';
                const number = item.flight_number || item.train_number || '';
                const depTime = item.dep_time || '';
                const arrTime = item.arr_time || '';
                const duration = item.duration || '';
                const price = item.price || 0;
                
                html += `
                    <div class="result-item" onclick="selectResult(${index})">
                        <div class="result-header">
                            <div class="result-type">
                                <span>${typeIcon}</span>
                                <span>${typeName} ${number}</span>
                            </div>
                            <div class="result-price">¥${price}</div>
                        </div>
                        <div class="result-details">
                            <div class="detail-item">
                                <div class="detail-label">出发时间</div>
                                <div class="detail-value">${depTime}</div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">到达时间</div>
                                <div class="detail-value">${arrTime}</div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">行程时间</div>
                                <div class="detail-value">${duration}</div>
                            </div>
                        </div>
                        <div class="result-meta">
                            <span>数据源：${item.source || '未知'}</span>
                            <span>更新时间：${item.crawl_time || ''}</span>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            resultsContent.innerHTML = html;
        }
        
        // 选择结果
        function selectResult(index) {
            const item = window.currentResults[index];
            alert(`已选择：${item.type === 'flight' ? '航班' : '火车'} ${item.flight_number || item.train_number} - ¥${item.price}`);
        }
        
        // 显示错误
        function showError(message) {
            const resultsContent = document.getElementById('resultsContent');
            resultsContent.innerHTML = `<div class="error">${message}</div>`;
        }
        
        // 检查API状态
        async function checkApiStatus() {
            try {
                const response = await fetch('/api/status');
                const data = await response.json();
                
                if (data.status === 'success') {
                    document.getElementById('apiStatus').textContent = 'API连接正常';
                    document.getElementById('apiStatus').style.background = '#4CAF50';
                } else {
                    document.getElementById('apiStatus').textContent = 'API连接异常';
                    document.getElementById('apiStatus').style.background = '#f44336';
                }
            } catch (error) {
                document.getElementById('apiStatus').textContent = 'API连接失败';
                document.getElementById('apiStatus').style.background = '#f44336';
            }
        }
        
        // 页面加载时检查API状态
        checkApiStatus();
        
        // 每30秒检查一次API状态
        setInterval(checkApiStatus, 30000);
    </script>
</body>
</html>
'''

if __name__ == '__main__':
    print("🚀 启动聚合数据API增强版服务器")
    print("=" * 60)
    print("🔧 支持真实机票和火车票数据获取")
    print("🧠 支持智能排序功能")
    print("=" * 60)
    
    if FLIGHT_API_KEY == "YOUR_FLIGHT_API_KEY":
        print("⚠️  警告：请先设置真实的API密钥")
        print("1. 访问 https://www.juhe.cn/ 注册账号")
        print("2. 申请机票和火车票API")
        print("3. 将API密钥替换到代码中")
        print("=" * 60)
    
    app.run(host='0.0.0.0', port=5000, debug=True)